package com.scap.authen.controller;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.scap.authen.service.MenuService;
import com.scap.authen.util.DataTable;

@Controller
@RequestMapping(value = "/menu")
public class MenuManagementController {

	@Autowired
	private MenuService voMenuService;

	@Autowired
	private ApplicationContext context;
	DataTable voDataTable = new DataTable();

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView getMenuPage(HttpServletRequest request) {
		
		ModelAndView voModelAndView = new ModelAndView("Application/menuManagement");
		voModelAndView.addObject("page", "Menu Management");
		voModelAndView.addObject("vaApplicationName", request.getParameter("vaApplicationName"));
		voModelAndView.addObject("vaApplicationId", request.getParameter("vaApplicationId"));

		return voModelAndView;
	}
	
	@RequestMapping(value = "/getMenu",method = RequestMethod.GET)
	public @ResponseBody String getMenu(
			HttpServletRequest request) {
		
		Map<String,Object> voMenu = new HashMap<String,Object>();
		
		voMenu.put("menu", voMenuService.getMenuByApplicationId(request.getParameter("vaApplicationId")));

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String json2 = gson.toJson(voMenu);

		return json2;
	}

	@RequestMapping(method = RequestMethod.POST)
	public @ResponseBody String manageMenu(
			HttpServletRequest request) {
		String vaStatus = "";
		String vaMessage = "";
		Map<String,String> voMessage = new HashMap<String,String>();
		Locale voLocale = RequestContextUtils.getLocale(request);
		
		vaStatus = voMenuService.insertMenu(request);
		
		if (vaStatus.equals("success")) {
			vaMessage = context.getMessage("alert.save.success", null, voLocale);
		} else {
			vaMessage = context.getMessage("alert.save.fail", null, voLocale);
		}
		
		voMessage.put("status", vaStatus);
		voMessage.put("message", vaMessage!=null?vaMessage.replace("_Name_", context.getMessage("class.MenuMapping", null, voLocale)):"");
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String json2 = gson.toJson(voMessage);

		return json2;
	}

	
}
